<?php

namespace app\index\controller;

use app\common\utils\WeChatUtils;
use app\index\logic\NoteLogic;
use app\index\logic\PayLogic;
use app\index\logic\UserLogic;
use think\Config;
use think\Controller;
use think\Loader;
use think\Log;

Loader::import('wxpay.WxPayJsApiPay');
Loader::import('wxpay.WxPayUnifiedOrder');
Loader::import('wxpay.WxPayNotify');

class Index extends Controller
{

    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    private function check(){
        $user_id = $this->getUserId();
        $we_chat = Config::get('WeChat');
        $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
        if ( empty($user_id)) {
            $utils->getUserCode('0');
            exit();
        }
    }

    public function index()
    {
        $this->check();
        return $this->view->fetch();
    }

    /**
     * ajax获取用户签列表
     * @return string
     */
    public function user_note_list(){
        $pagesize = 10;
        $pagenumber = $this->request->post('pagenum',1);
        $user_id = $this->getUserId();
        $logic = new NoteLogic();
        $data = $logic->getUserNoteList($user_id,$pagenumber,$pagesize);
        $this->view->assign('data', $data);
        $this->view->engine->layout(false);
        return $this->view->fetch('user_note_list');
    }

    /**
     * ajax获取用户签列表
     * @return string
     */
    public function ajax_user_note_list(){
        $page_num = $this->request->post('page_num',1);
        $page_size = $this->request->post('page_size',10);
        $user_id = $this->request->post('user_id');
        $logic = new NoteLogic();
        $data = $logic->getUserNoteList($user_id,$page_num,$page_size);
        return json($data);
    }

    /**
     * 签详情
     * @return string
     */
    public function detail(){
        $this->check();
        $user_note_id = $this->request->param('user_note_id');
        $logic = new NoteLogic();
        $data = $logic->getNoteById($user_note_id);
        $this->view->assign('note',$data);
        if($data['user_note']['is_solve'] == 1 || $data['temple']['money'] == 0){
            return $this->view->fetch();
        }else{
            $result = $logic->createOrUpdateOrder($data['user_note']['id']);
            if($result['status'] == 1){
                $order = $result['data'];
                $user_id = $this->getUserId();
                $openid = model('User')->where(array('id'=>$user_id))->value('open_id');
                $this->makeWeChatPay($openid,'解签','上善签解签', $order['order_number'], $order['money']);
            }else{
                return $this->view->fetch();
            }
            return $this->view->fetch('detail_pay');
        }
    }

    /**
     * ajax获取签内容
     * @return \think\response\Json
     */
    public function ajax_note_detail(){
        $user_note_id = $this->request->post('user_note_id');
        $logic = new NoteLogic();
        $data = $logic->getNoteById($user_note_id);
        return json($data);
    }

    /**
     * ajax获取用户id
     * @return \think\response\Json
     */
    public function ajax_user_info(){
        $open_id = $this->request->post('open_id');
        $user_id = model('User')->where(array('open_id'=>$open_id))->value('id');
        if(!$user_id){
            return json(['success'=>false]);
        }else{
            return json(['success'=>true,'user_id'=>$user_id]);
        }
    }

    /**
     * ajax创建用户
     * @return \think\response\Json
     */
    public function ajax_create_user(){
        $open_id = $this->request->post('open_id');
        $nickname = $this->request->post('nickname');
        $logic = new UserLogic();
        $user = $logic->createUser($open_id,$nickname);
        if($user){
            return json(['success'=>true,'user_id'=>$user['id']]);
        }else{
            return json(['success'=>false]);
        }
    }


    /**
     * ajax获取解签内容
     * @return \think\response\Json
     */
    public function solve_note_content(){
        $user_note_id = $this->request->post('user_note_id');
        $user_note = model('UserNote')
            ->where(array('id'=>$user_note_id))
            ->find();
        $temple_id = model('Note')->where(array('id'=>$user_note['note_id']))->value('temple_id');
        $money = model('Temple')->where(array('id'=>$temple_id))->value('money');
        if($user_note['is_solve'] == 0 && $money !=0){
            return json(array('success'=>false,'msg'=>'对不起，支付后才能解签！'));
        }
        if($user_note['is_solve'] == 0 && $money == 0){
            model('UserNote')
                ->where(array('id'=>$user_note_id))
                ->setField('is_solve',1);
        }
        $prefix = config('database.prefix');
        $solve_note_ids = model('Note')
            ->where(array('id'=>$user_note['note_id']))
            ->value('solve_note_ids');
        $solve_note_list = model('SolveNote')
            ->with('type')
            ->where($prefix.'solve_note.id','in',$solve_note_ids)
            ->select();
        return json(array('success'=>true,'data'=>$solve_note_list));
    }

    public function weChatPayRtn(){
        Log::write('begin notify');
        $notify = new PayNotifyCallBack();
        $notify->Handle(true);
    }

    protected function getUserId(){
        $user = session('user');
        if(!$user || !isset($user)){
            return '';
        }
        return $user['id'];
    }

    /**
     * 构造微信支付页面
     * @param $openid
     * @param $description
     * @param $title
     * @param $order_number
     * @param $money
     * @throws \WxPayException
     */
    private function makeWeChatPay($openid,$description, $title, $order_number, $money)
    {

        $tools = new \JsApiPay();
        $openId = $openid;
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $description =mb_substr($description,0,20,'utf-8');
        $title =mb_substr($title,0,10,'utf-8');
        $input->SetBody($description);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_number);
        $input->SetTotal_fee($money*100);
//        $input->SetTotal_fee(1);
//        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($title);
        $url = 'http://'.$_SERVER['HTTP_HOST']."/index/index/weChatPayRtn";
        $input->SetNotify_url($url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->assign('editAddress', $editAddress);
        $this->assign('money', $money);
    }

}
class PayNotifyCallBack extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            return false;
        }
        $money = $data['total_fee'];
        Log::write('out_trade_no:'.$data['out_trade_no']);
        $logic = new PayLogic();
        $success = $logic->weChatPaySuccess($data['out_trade_no'],$money,0);
        Log::write('out_trade_no:'.$data['out_trade_no']);
        if($success == 1){
            return true;
        }else{
            return false;
        }
    }

}